package cz.khfotbal.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cz.khfotbal.dao.ArticleDao;
import cz.khfotbal.domain.Article;

@Repository
@Transactional
public class ArticleDaoImpl implements ArticleDao {

	@Autowired
	private SessionFactory sessionFactory;

	private Session session;

	public List<Article> findAllArticles(String category) {
		session = sessionFactory.getCurrentSession();
		List<Article> list = session.createQuery("from Article where category = '"+category+"' order by date desc").list();
		return list;
	}
	
	public List<Article> findAllArticlesMain() {
		session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Article where category != 'informace' and category != 'clanky' order by date desc"); 
		query.setCacheable(true);
		List<Article> list = query.list();
		return list;
	}

	public void saveArticle(Article article) {
		session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(article);
	}

	public void updateArticle(Article article) {
		session = sessionFactory.getCurrentSession();
		session.merge(article);
	}

	public Article findArticleById(int id) {
		session = sessionFactory.getCurrentSession();
		Article article = (Article) session.createQuery("from Article where id = "+id).uniqueResult();
		return article;
	}

	public void deleteArticle(Article article) {
		session = sessionFactory.getCurrentSession();
		session.delete(article);
	}

	public List<Article> findFiveInformation() {
		session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Article where category = 'informace' and priority < 6 order by priority");
		query.setCacheable(true);
		List<Article> list = query.list();
		return list;
	}

	public List<Article> findFiveClanek() {
		session = sessionFactory.getCurrentSession();
		List<Article> list = session.createQuery("from Article where category = 'clanky' and zobrazit = 'ano' order by date").list();
		return list;
	}
}
